<?php
/**
 * Created by PhpStorm.
 * User: 虚空之翼 <183700295@qq.com>
 * Date: 16/3/25
 * Time: 09:12
 * 微信事件接口
 */
namespace app\admin\controller;
use app\home\model\Picture;
use com\wechat\Wechat;
use com\wechat\TPWechat;
use think\Config;
use think\Controller;
use app\admin\model\Sign;
use app\admin\model\WechatUser;
use app\admin\model\CourseSign;
use think\Db;

class Service extends Controller
{

    // 服务号接收的应用
    public function event() {
        $Wechat = new TPWechat(Config::get('party'));
//        $Wechat->valid();

        $type = $Wechat->getRev()->getRevType();
        switch ($type) {
            case Wechat::MSGTYPE_EVENT:  // 事件
                $event = $Wechat->getRev()->getRevEvent();
                switch ($event['event']) {
                    case 'subscribe':
                        $openid = $Wechat->getRevFrom();
                        $data = $Wechat->getUserInfo($openid);
                        // mysql 数据库3字节UTF8编码 微信昵称有些包含4字节UTF8编码的emoji标签
                        $data['nickname'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u','',$data['nickname']);
                        if ($data['tagid_list']){
                            $data['tagid_list'] = json_encode($data['tagid_list']);
                        }
                        $id = WechatUser::where('openid',$openid)->value('id');
                        if (empty($id)){
                            // 添加数据
                            WechatUser::create($data);
                        }else{
                            $data['unsubscribe_time'] = 0;
                            $data['status'] = 1;
                            // 之前有过关注  更新数据
                            WechatUser::where('id' ,$id)->update($data);
                        }
                        $newsData = array(
                            '0'=> array(
                                'Title' => "欢迎关注“点对点教育”公众号",
                                'Description' => "点对点助您金榜题名",
                                'PicUrl' => "http://mp.csppat.com/DDDeducation/public/admin/images/logo.png",
                                'Url' => "http://www.popedu.net/",
                            ),
                        );
                        $Wechat->news($newsData)->reply();
                        break;
                    case 'unsubscribe':
                        $openid = $Wechat->getRevFrom();
                        WechatUser::where('openid' ,$openid)->update(['subscribe' => 0,'unsubscribe_time' => time(),'status' => 0,'role' => 0,'review_status' => 0,'order_id' => '','vip_id' => '','school_id' => '','party' => '','tel' => '']);
                        break;
                    case Wechat::EVENT_MENU_CLICK:
                        switch ($event['key']){
                            case 'Sign_001' :
                                $openid = $Wechat->getRevFrom();  // 获取签到人id
                                $User = WechatUser::where('openid',$openid)->field('review_status,role,sign_time')->find();
                                if ($User['review_status'] == 0 || $User['role'] == 1){
                                    $word = "抱歉~~，您暂无签到权限，请确认是否认证或是否为学员 !";
                                    $Wechat->text($word)->reply();
                                    break;
                                }else{
                                    if (date('w') == 1){
                                        // 周一
                                        $word = "今日休息无需签到哦，要好好休息，保证明天有更好的状态去迎接新的学习任务~~";
                                        $Wechat->text($word)->reply();
                                        break;
                                    }else{
                                        if (time() < strtotime(date('Y-m-d 05:00:00'))){
                                            $word = "现在是晚上睡眠时间，保证好的休息，才能有好的身体和好的状态去应对学习内容~~";
                                            $Wechat->text($word)->reply();
                                            break;
                                        }elseif(time() < strtotime(date('Y-m-d 05:40:00')) && time() >= strtotime(date('Y-m-d 05:00:00'))){
                                            $word = "还未到签到时间，一定要休息好，不要起得太早哦~~";
                                            $Wechat->text($word)->reply();
                                            break;
                                        }else{
                                            if (!empty($User['sign_time']) && ($User['sign_time'] > strtotime(date('Y-m-d 00:00:00')) && $User['sign_time'] <= strtotime(date('Y-m-d 23:59:59')))){
                                                //已经签到
                                                $word = "今日已签到，请安心学习、生活和工作，加油！";
                                                $Wechat->text($word)->reply();
                                                break;
                                            }else{
                                                if (time() <= strtotime(date('Y-m-d 08:00:00')) && time() >= strtotime(date('Y-m-d 05:40:00'))){
                                                    // 未签到 保存数据库
                                                    $result = WechatUser::where('openid',$openid)->update(['sign_time' => time(),'score' => ['exp','`score`+0.5']]);
                                                    if ($result){
                                                        $Sign = new Sign();
                                                        $Sign->save(['openid' => $openid,'create_time' => time()]);
                                                        $people = WechatUser::where(['review_status' => 1,'sign_time' => ['neq','null']])->whereTime('sign_time','d')->count(); // 已经签到的人数
                                                        $before = mktime(0, 0, 0,date('m'), 1, date('Y'));
                                                        $summary_sum = Db::name('summary')->where(['openid' => $openid,'status' => 0,'create_time' => ['between', [$before, time()]]])->count();
                                                        $word = "🎉🎉🎉签到成功，你是今日第".($people+1)."位签到的同学！本月已提交".$summary_sum."篇总结！聪明出于勤奋，天才在于积累。继续加油哦~🌹";
                                                        $Wechat->text($word)->reply();
                                                        break;
                                                    }else{
                                                        $word = "sorry~~，签到失败，请重试！";
                                                        $Wechat->text($word)->reply();
                                                        break;
                                                    }
                                                }else{
                                                    $word = "签到超时，请在【05:40——08:00】时间段签到，按时起床、早餐、晨读...，一日之计在于晨！";
                                                    $Wechat->text($word)->reply();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                break;
                            case "Sign_002":
                                $newsData = array(
                                    '0'=> array(
                                        'Title' => "【排行榜】 签到 && 总结 && 测试",
                                        'Description' => "赶快点进去查看小伙伴们的排名吧~~",
                                        'PicUrl' => "http://mp.csppat.com/DDDeducation/public/home/images/rank/12.png",
                                        'Url' => "http://mp.csppat.com/DDDeducation/public/index.php/home/rank/index",
                                    ),
                                );
                                $Wechat->news($newsData)->reply();
                                break;
                            case "Sign_003":
                                $openid = $Wechat->getRevFrom();  // 获取签到人id
                                $User = WechatUser::where('openid',$openid)->field('review_status,role,type')->find();
                                if ($User['review_status'] == 0 || $User['role'] == 1){
                                    $word = "抱歉~~，您暂无查看权限，请确认是否认证或是否为学员 !";
                                    $Wechat->text($word)->reply();
                                    break;
                                }else{
                                    if (date('w') == 1){
                                        // 周一
                                        $word = "今日无需背单词，好好休息，以更好的状态去迎接明天的学习任务~~";
                                        $Wechat->text($word)->reply();
                                        break;
                                    }else{
                                        $type = $User['type']; // 1 考研 2 专升本 3 四六级 4 雅思 5 托福
                                        $wordSign = Db::name('word_sign')->where(['openid' => $openid,'type' => $type])->field('create_time,day')->find();
                                        if (empty($wordSign)){
                                            // 暂无单词记录
                                            $Words = Db::name('word')->where(['type' => $type,'day' => 1])->field('front_cover,id,title,description')->find();
                                            if (empty($Words)){
                                                // 暂无第一天数据
                                                $word = "抱歉~~该类型单词暂无数据，请等待。";
                                                $Wechat->text($word)->reply();
                                                break;
                                            }else{
                                                $url = Picture::where('id',$Words['front_cover'])->value('path');
                                                $newsData = array(
                                                    '0'=> array(
                                                        'Title' => $Words['title'],
                                                        'Description' =>$Words['description'],
                                                        'PicUrl' => "http://mp.csppat.com/DDDeducation/public".$url,
                                                        'Url' => "http://mp.csppat.com/DDDeducation/public/index.php/home/word/detail/id/".$Words['id'],
                                                    ),
                                                );
                                                $Wechat->news($newsData)->reply();
                                                break;
                                            }          
                                        }else{
                                            // 有单词记录
                                            if ($wordSign['create_time'] >= strtotime(date('Y-m-d 00:00:00')) && $wordSign['create_time'] <= strtotime(date('Y-m-d 23:59:59'))){
                                            // 当天之内
                                                $Words = Db::name('word')->where(['type' => $type,'day' => $wordSign['day']])->field('front_cover,id,title,description')->find();
                                            }else{
                                                $Words = Db::name('word')->where(['type' => $type,'day' => $wordSign['day']+1])->field('front_cover,id,title,description')->find();
                                            }
                                            if (empty($Words)){
                                                // 暂无第一天数据
                                                $word = "抱歉~~该类型单词暂无更新，前往_<a href=\"http://mp.csppat.com/DDDeducation/public/index.php/home/Word/news\">历史记录</a>_温故知新。";
                                                $Wechat->text($word)->reply();
                                                break;
                                            }else{
                                                $url = Picture::where('id',$Words['front_cover'])->value('path');
                                                $newsData = array(
                                                    '0'=> array(
                                                        'Title' => $Words['title'],
                                                        'Description' =>$Words['description'],
                                                        'PicUrl' => "http://mp.csppat.com/DDDeducation/public".$url,
                                                        'Url' => "http://mp.csppat.com/DDDeducation/public/index.php/home/word/detail/id/".$Words['id'],
                                                    ),
                                                );
                                                $Wechat->news($newsData)->reply();
                                                break;
                                            }
                                        }
                                    }
                                }
                            case "Sign_004":
                                $Wechat->image('89VEb8v6Ordnz47SKNIu2lHzMtwFPBNYfcIw-83pxGo')->reply();
                                break;
                            default:
                                break;
                        }
                        break;
                    case Wechat::EVENT_MENU_SCAN_WAITMSG:
                        switch ($event['key']){
                            case 'Scan_001':
                                $openid = $Wechat->getRevFrom();  // 获取签到人id
                                $Info = $Wechat->getRevScanInfo();
                                $result = $Info['ScanResult']; // 扫码结果
                                $Res =  CourseSign::where(['c_id' => $result,'openid' => $openid])->field('status')->find();
                                if (empty($Res)){
                                    $Wechat->text('抱歉~~，二维码错误或未分配该课程！')->reply();
                                    break;
                                }else{
                                    $course = Db::name('course')->where('id',$result)->field('start_time,end_time')->find();
                                    $time = time();
                                    switch ($Res['status']){
                                        case 0:
                                            if ($time < $course['start_time']-3600){
                                                // 早于 1h
                                                $Wechat->text('抱歉~~，未到签到时间，请在开始时间前1h内进行签到！')->reply();
                                                break;
                                            }elseif ($time >= ($course['start_time']-3600) && $time <= $course['start_time']+1800){
                                                // 正常
                                                CourseSign::where(['c_id' => $result,'openid' => $openid])->update(['status' => 1,'signout_time' => $time,'signin_time' => $time,'reason' => 1]);
                                                WechatUser::where(['openid' => $openid])->setInc('score');
                                                $Wechat->text("🎉🎉🎉签到成功，本次课程你准时签到，要专心听讲，课后可以 _<a href=\"http://mp.csppat.com/DDDeducation/public/index.php/home/Evaluate/index/id/{$result}\">去评价</a>_哦~~")->reply();
                                                break;
                                            }elseif ($time > $course['start_time']+1800 && $time <= $course['end_time']-1800){
                                                // 迟到
                                                CourseSign::where(['c_id' => $result,'openid' => $openid])->update(['status' => 2,'signout_time' => $time,'signin_time' => $time,'reason' => 2]);
                                                WechatUser::where(['openid' => $openid])->setDec('score');
                                                $Wechat->text("🎉🎉🎉签到成功，本次课程你属于迟到，下次记得要准时，课后可以_<a href=\"http://mp.csppat.com/DDDeducation/public/index.php/home/Evaluate/index/id/{$result}\">去评价</a>_哦~~")->reply();
                                                break;
                                            }elseif ($time > $course['end_time']-1800){
                                                // 课前 未签到 课后不能签到
                                                CourseSign::where(['c_id' => $result,'openid' => $openid])->update(['status' => 3,'signout_time' => $time,'signin_time' => $time,'reason' => 2]);
                                                WechatUser::where(['openid' => $openid])->setDec('score',3);
                                                $Wechat->text('抱歉~~，本次课程你属于旷课，下次要记得课前准时签到哦！加油~~')->reply();
                                                break;
                                            }
                                            break;
                                        case 1:
                                            $Wechat->text("抱歉~~，禁止重复签到，该课程你【正常签到】，_<a href=\"http://mp.csppat.com/DDDeducation/public/index.php/home/Evaluate/index/id/{$result}\">去评价</a>_")->reply();
                                            break;
                                        case 2:
                                            $Wechat->text("抱歉~~，禁止重复签到，该课程你【已迟到】，_<a href=\"http://mp.csppat.com/DDDeducation/public/index.php/home/Evaluate/index/id/{$result}\">去评价</a>_")->reply();
                                            break;
                                        case 3:
                                            $Wechat->text('抱歉~~，禁止重复签到，该课程你【已旷课】！')->reply();
                                            break;
                                        case 4:
                                            $Wechat->text('抱歉~~，禁止重复签到，该课程你【已请假】！')->reply();
                                            break;
                                        default :
                                            $Wechat->text('抱歉~~，系统参数错误，请重试！')->reply();
                                            break;
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
                break;
//            case Wechat::MSGTYPE_IMAGE:
//                $Re = $Wechat->getRevPic();
//                $Wechat->text($Re['mediaid'])->reply();
//                break;
            default:
                $Wechat->text("加油哦~~点对点助您金榜题名！")->reply();
                break;
        }

    }
    
    // 创建订阅号菜单
    public function menu() {
        $menu["button"] = array(
            array(
                "name" => "VIP服务",
                'sub_button' => array (
                    0 => array(
                        'type' => 'click',
                        'name' => '每日签到',
                        'key'  => 'Sign_001'
                    ),
                    1 => array(
                        'type' => 'click',
                        'name' => '每日单词',
                        'key'  => 'Sign_003'
                    ),
                    2 => array(
                        'type' => 'scancode_waitmsg',
                        'name' => '上课签到',
                        'key'  => 'Scan_001'
                    ),
                    3 => array(
                        'type' => 'view',
                        'name' => '总结+作业',
                        'url'  => 'http://mp.csppat.com/DDDeducation/public/index.php/home/Journal/home'
                    ),
                    4 => array(
                        'type' => 'view',
                        'name' => '测试提交',
                        'url'  => 'http://mp.csppat.com/DDDeducation/public/index.php/home/test/index'
                    ),
                ),
            ),
            array(
                "name" => "我的",
                'sub_button' => array (
                    
                    0 => array(
                        'type' => 'click',
                        'name' => '* 排行榜 *',
                        'key'  => 'Sign_002'
                    ),
                    1 => array(
                        'type' => 'view',
                        'name' => '成功学员',
                        'url'  => 'https://mp.weixin.qq.com/mp/homepage?__biz=MzU0NjU0MTA5NA%3D%3D&hid=4&sn=6fbf3533707ef3581d2d687db586b8e5'
                    ),
                    2 => array(
                        'type' => 'view',
                        'name' => '每日一句',
                        'url'  => 'http://mp.csppat.com/DDDeducation/public/index.php/home/Translate/index'
                    ),
                    3 => array(
                        'type' => 'view',
                        'name' => '私人定制',
                        'url'  => 'http://mp.csppat.com/DDDeducation/public/index.php/home/check/index'
                    ),
                    4 => array(
                        'type' => 'view',
                        'name' => '个人中心',
                        'url' => 'http://mp.csppat.com/DDDeducation/public/index.php/home/user/index',
                    ),
                ),
            ),
            array(
                "name" => "焦点汇聚",
                'sub_button' => array (
                    0 => array(
                        'type' => 'view',
                        'name' => '微官网',
                        'url'  => 'http://56048742.m.weimob.com/weisite/home?pid=56048742&bid=1016090389&wechatid=fromusername'
                    ),
                    1 => array(
                        'type' => 'view',
                        'name' => '微商城',
                        'url'  => 'http://56048742.m.weimob.com/vshop/56048742/Index?PageId=693159&IsPre=1&ShopId=0'
                    ),
                    2 => array(
                        'type' => 'view',
                        'name' => '预约咨询',
                        'url'  => 'http://56048742-yuyue.m.weimob.com/56048742/15930'
                    ),
                    3 => array(
                        'type' => 'click',
                        'name' => '掌上研招',
                        'key'  => 'Sign_004'
                    ),
                    4 => array(
                        'type' => 'view',
                        'name' => '用户中心',
                        'url'  => 'http://56048742.m.weimob.com/vshop/56048742/UserCenter/UserCenter'
                    ),
                ),
            ),
        );

        $Wechat = new TPWechat(Config::get('party'));
        $result = $Wechat->createMenu($menu);

        if($result) {
            return $this->success('提交成功');
        } else {
            return $this->error('错误代码：'.$Wechat->errCode.'，消息：'.$Wechat->errMsg);
        }
    }
}